package bgate.connector;



import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

public class WriterThread implements Runnable{// extends Thread {

    private boolean _running = true;
    private Vector outgoingMessages;
    private PrintStream _out;
    private long delayTime =50L;
    private int i;
    private String message;

    WriterThread(PrintStream out) {
       
        _out = out;
        outgoingMessages = new Vector();
    }

    //13\\public synchronized void run() {
    public void run() {

        if(_running){
            flushOutputQueue();
        }

    }

    public void flushOutputQueue() {
        //\\int i;

        while (outgoingMessages.size() > 0) {
            message = null;
            message = (String) outgoingMessages.elementAt(0);
            //\\System.out.println("Send:" + message);
            outgoingMessages.removeElementAt(0);
            //_out.print(message + "\r\n");
            byte[] outMsg = null;
            //outMsg = message.getBytes();

            try {
                //outMsg = message.getBytes("UTF-8");
                outMsg = new byte[message.getBytes("UTF-8").length];

                for(i = 0; i < message.getBytes("UTF-8").length; i++){
                    outMsg[i] = message.getBytes("UTF-8")[i];
                }
           //     outMsg[outMsg.length - 1] = (byte)3;
                /*
                System.out.println("outMsg:" +  outMsg.length);
                
                for(i = 0; i < outMsg.length; i++){
                    System.out.println(outMsg[i]);
                }
                 */
                 
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }

            if(outMsg != null){                
                try {
                    _out.write(outMsg);
                    //_out.write("\r".getBytes());
                    //_out.write((byte)3);
                    _out.flush();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        //_out.flush();
    }

    public synchronized void queueMessage(String s) {
        outgoingMessages.addElement(s);
        notify();
    }

    public void halt() {
        _running = false;
    }
}

